package dk.pun.dums.client.presenter;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;

import dk.pun.dums.client.DUMSServiceAsync;
import dk.pun.dums.client.view.ViewCharacterView;
import dk.pun.dums.shared.character.CharacterData;
import dk.pun.dums.shared.character.ExperiencePoints;

public class ViewCharacterPresenter implements Presenter, dk.pun.dums.client.view.ViewCharacterView.Presenter {

	private final transient DUMSServiceAsync rpcService;
	private final transient ViewCharacterView view;

	public ViewCharacterPresenter(final ViewCharacterView view, final CharacterData characterData, final DUMSServiceAsync rpcService) {
		this.view = view;
		this.view.setPresenter(this);
		this.rpcService = rpcService;
		this.view.setCharacterData(characterData);
	}
	
	@Override
	public void onCharacterDataUpdated(final CharacterData characterData) {
		this.rpcService.updateCharacterData(characterData, new AsyncCallback<Void>() {

			@Override
			public void onSuccess(final Void result) {
				// Nothing to do on success
			}

			@Override
			public void onFailure(final Throwable caught) {
				GWT.log("Failed to update character data: ", caught);
			}
		});
	}

	@Override
	public void onAddExperience(final CharacterData characterData, final ExperiencePoints experience) {
		characterData.addExperience(experience);
		this.rpcService.updateCharacterData(characterData, new AsyncCallback<Void>() {

			@Override
			public void onSuccess(final Void result) {
				view.addExperience(experience);
			}

			@Override
			public void onFailure(final Throwable caught) {
				GWT.log("Failed to update character data: ", caught);
			}
		});
	}

	@Override
	public void go(final HasWidgets container) {
		container.clear();
		container.add(this.view.asWidget());
	}

}
